﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Grid : BasicPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BasicInit();
            if (!IsPostBack)
            {
                FillData();
            }
        }

        public void FillData()
        {
            var sql = "select * from Action";
            var dt = DbHelper.GetDatatable(sql);
            Gv1.DataSource = dt;
            Gv1.DataBind();
        }

        private string GetValue(int rowIndex,int colIndex)
        {
            var controls = Gv1.Rows[rowIndex].Cells[colIndex];
            var res = controls.Controls.Count > 0 ? ((TextBox)controls.Controls[0]).Text : controls.Text;
            return res;
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            var sql = "select * from Action";
            var dt = DbHelper.GetDatatable(sql);
            dt.Rows.Add(dt.NewRow());
            Gv1.DataSource = dt;
            Gv1.DataBind();
            if(Gv1.PageIndex != Gv1.PageCount - 1)
            {
                Gv1.PageIndex = Gv1.PageCount - 1;
                Gv1.DataSource = dt;
                Gv1.DataBind();
            }
            Gv1.EditIndex = Gv1.Rows.Count - 1;
            Gv1.DataSource = dt;
            Gv1.DataBind();
        }

        protected void Gv1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            Gv1.PageIndex = e.NewPageIndex;
            FillData();
        }

        protected void Gv1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetValue(e.RowIndex, 0);
            var sql = string.Format("delete from Action where id = {0}",id);
            DbHelper.ExeOreaption(sql);
            FillData();
        }

        protected void Gv1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            Gv1.EditIndex = e.NewEditIndex;
            FillData();
        }

        protected void Gv1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            Gv1.EditIndex = -1;
            FillData();
        }

        protected void Gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var isString = GetValue(e.RowIndex, 0);
            var actionName = GetValue(e.RowIndex, 1);
            var actionContnet = GetValue(e.RowIndex, 2);
            var isok = int.TryParse(isString,out int id);
            if (isok)
            {
                var sql = string.Format("update Action set ActionName = '{0}' ,ActionContent = '{1}' where id = {2}",actionName,actionContnet,id);
                DbHelper.ExeOreaption(sql);
                Gv1.EditIndex = -1;
                FillData();
            }        
        }
    }
}